<template>
	<div class="tabel_Background">
		<div class="tabel_Background-wra">
			<div class="chart pt-10">
				<div id="mapChart" class="mapChart"></div>
				<div class="mapChoose">
					<span v-for="(item, index) in selectedMaps" :key="item.code">
						<span class="title" @click="chooseMap(item, index)">{{
              item.name == "china" ? "全国" : item.name
            }}</span>
						<span class="icon" v-show="index + 1 != selectedMaps.length">></span>
					</span>
				</div>
				<div class="year-cls">
					<el-select size="mini" clearable style="width:100%;height:100%;" :style="setBackground" v-model="data.yearstr"
					 @change="changeMapData(chinaCode,curMapName)" :popper-append-to-body="false">
						<el-option v-for="item in timeDistribution" :key="item.value" :label="item.label" :value="item.label">
						</el-option>
					</el-select>
				</div>
			</div>
		</div>
	</div>
</template>

<script>
	import {
		getChina
	} from "@/api/index";
	import axios from "axios";
	import {
		mapCode
	} from "@/assets/js/map/mapCode.js";
	import {
		_debounce
	} from "@/utils/common.js";


	export default {
		name: "ChinaData",
		props: {
			title: String
		},

		data() {
			return {
				myChart: null,
				chinaCode: 100000,
				nullData: '',
				oldCraft: '',
				oldCategory: '',
				curMapName: "china", // 当前地图名
				selectedMaps: [{
					name: "china",
					code: "100000"
				}],
				data: {
					yearstr: "",
					province: "",
					city: "",
					craft: "",
					category: "",
				},
				mapData: [],
				setBackground: {
					backgroundImage: "url(" + require("../../assets/btn_year@2x.png") + ")",
					backgroundRepeat: "no-repeat",
					backgroundSize: "100% 100%"
				},
				timeDistribution: [],
			};
		},

		methods: {
			changeMapData(chinaCode, curMapName) {
				this.selectedMaps = [{
					name: "china",
					code: "100000"
				}];
				this.getMapData(chinaCode, curMapName);
			},

			// 绘制地图
			async drawMapChart(mapName, mapJSON) {
				let arr = await this.initMapData(mapJSON);
				// console.log(arr);
				let max = 0;
				for (let a = 0; a < arr.length; a++) {
					var max1 = arr[a].value[2];
					if (max1 > max) {
						max = max1;
					}
				};
				// console.log(max);

				if (
					this.myChart != null &&
					this.myChart != "" &&
					this.myChart != undefined
				) {
					this.myChart.dispose();
				};
				this.myChart = this.$echarts.init(document.getElementById("mapChart"));
				this.$echarts.registerMap(mapName, mapJSON);
				this.myChart.setOption({
					// 背景颜色
					// backgroundColor: "#404a59",
					// 提示浮窗样式
					tooltip: {
						show: true,
						trigger: "item",
						alwaysShowContent: false,
						backgroundColor: "#0C121C",
						borderColor: "rgba(0, 0, 0, 0.16);",
						hideDelay: 100,
						triggerOn: "mousemove",
						enterable: true,
						textStyle: {
							color: "#DADADA",
							fontSize: "12",
							width: 20,
							height: 30,
							overflow: "break"
						},
						showDelay: 100,
						formatter(params) {
							if (params.value[2]) {
								return `地区：${params.name}</br>井数：${params.value[2]}`;
							} else if (!params.value[2]) {
								return `地区：${params.name}`;
							}
							// console.log(params);

						}
					},
					// 地图配置
					geo: {
						map: mapName,
						selectedMode: "false", // 是否允许选中多个区域
						roam: true, // 是否开启鼠标缩放和平移漫游
						// zoom: 1.2,
						layoutCenter: ["50%", "70%"], //位置
						layoutSize: "160%", //大小
						aspectScale: 0.75, // 地图的长宽比
						label: {
							// 通常状态下的样式
							normal: {
								show: false,
								textStyle: {
									color: "#fff"
								}
							},
							// 鼠标放上去的样式
							emphasis: {
								textStyle: {
									color: "#fff"
								}
							}
						},
						regions: [{
							name: "南海诸岛",
							itemStyle: {
								// 隐藏地图
								normal: {
									opacity: 0 // 为 0 时不绘制该图形
								}
							},
							label: {
								show: false // 隐藏文字
							}
						}],
						// 地图区域的样式设置
						itemStyle: {
							normal: {
								borderColor: "rgba(107, 211, 255, 1.0)",
								borderWidth: 1.5,
								areaColor: {
									type: "radial",
									x: 0.5,
									y: 0.5,
									r: 0.8,
									colorStops: [{
											offset: 1,
											color: "rgba(53, 185, 255, 0.0)" // 0% 处的颜色
										},
										{
											offset: 1,
											color: "rgba(29, 157, 255, 0.2)" // 100% 处的颜色
										}
									],
									globalCoord: false // 缺省为 false
								},
								shadowColor: "rgba(60, 118, 255, 1.0)",
								shadowOffsetX: -2,
								shadowOffsetY: 2,
								shadowBlur: 20,	
								
								// borderColor: "rgba(147, 235, 248, 1)",
								// borderWidth: 1,
								// areaColor: {
								// 	type: "radial",
								// 	x: 0.5,
								// 	y: 0.5,
								// 	r: 0.8,
								// 	colorStops: [{
								// 			offset: 0,
								// 			color: "rgba(147, 235, 248, 0)", // 0% 处的颜色
								// 		},
								// 		{
								// 			offset: 1,
								// 			color: "rgba(147, 235, 248, .2)", // 100% 处的颜色
								// 		},
								// 	],
								// 	globalCoord: false, // 缺省为 false
								// },
								// shadowColor: "rgba(128, 217, 248, 1)",
								// shadowOffsetX: -2,
								// shadowOffsetY: 2,
								// shadowBlur: 10,

							},
							// 鼠标放上去高亮的样式
							emphasis: {
								areaColor: "#389BB7",
								borderWidth: 0
							}
						}
					},

					visualMap: [{
						// 是否展示左下角，即是是false，也仅是不显示，不影响数据的映射
						show: false,
						// 上下端文字
						text: ["高", "低"],
						// 最小值和最大值，必须指定
						min: 0,
						max: max * 1.2,
						// 位置
						left: "2%",
						bottom: "2%",
						// 是否展示滑块
						calculable: false,
						// 指定映射的数据，对应的是option.series，这里根据自己的实际需要进行配置
						seriesIndex: [0],
						// 从下到上的颜色
						inRange: {
							color: ['#002e4f', '#13b4ff']
						},
						//字体颜色
						textStyle: {
							color: "#fff",
							map: "china"
						}
					}, {
						// 是否展示左下角，即是是false，也仅是不显示，不影响数据的映射
						show: true,
						// 上下端文字
						text: ["高", "低"],
						// 最小值和最大值，必须指定
						min: 0,
						max: max * 1.2,
						// 位置
						left: "2%",
						bottom: "2%",
						// 是否展示滑块
						calculable: true,
						// 指定映射的数据，对应的是option.series，这里根据自己的实际需要进行配置
						seriesIndex: [1],
						// 从下到上的颜色
						inRange: {
							color: ['#e8df5c', '#d47611']
						},
						//字体颜色
						textStyle: {
							color: "#fff",
							map: "china"
						}
					}],

					series: [{
							type: "map",
							roam: true,
							zoom: 1,
							geoIndex: 0,
							label: {
								// 通常状态下的样式
								normal: {
									show: true,
									textStyle: {
										color: "#fff",
									},
								},
								// 鼠标放上去的样式
								emphasis: {
									textStyle: {
										color: "#640000",
									},
								},
							},
							data: arr,
						},
						{
							type: "scatter",
							coordinateSystem: "geo",
							roam: true, // 是否开启鼠标缩放和平移漫游
							symbol: "pin",
							// legendHoverLink: true,
							symbolSize: (rawValue, params) => {
								// console.log(rawValue, params)
								if (rawValue[2] < 1000) {
									params.symbolSize = [42, 42]
								} else if (rawValue[2] < 10000) {
									params.symbolSize = [55, 55]
								} else {
									params.symbolSize = [65, 65]
								}
								return params.symbolSize
							},
							// 这里渲染标志里的内容以及样式
							label: {
								show: true,
								formatter(value) {
									return value.data.value[2];
								},
								color: "#fff",
							},
							// 标志的样式
							itemStyle: {
								normal: {
									color: "rgba(255, 0, 0, 0.7)",
									shadowBlur: 2,
									shadowColor: "D8BC37",
								},
							},
							// 数据格式，其中name,value是必要的，value的前两个值是数据点的经纬度，其他的数据格式可以自定义
							// 至于如何展示，完全是靠上面的formatter来自己定义的
							data: arr,
							showEffectOn: "render",
							rippleEffect: {
								brushType: "stroke",
							},
							hoverAnimation: true,
							zlevel: 1,

						}
					]
				});

				this.myChart.on("click", params => {
					const map = mapCode[params.name];
					if (mapJSON.features[0].properties.level == "province") {
						this.data.province = params.name;
						this.data.city = "";
					}
					if (mapJSON.features[0].properties.level == "city") {
						this.data.city = params.name;
					}
					if (map) {
						this.curMapName = params.name;
						this.getMapData(map, params.name);

						// 为地图标题菜单存入（过滤同一地图多次点击情况）点击地图信息
						let selectedCodes = [];
						this.selectedMaps.forEach(item => selectedCodes.push(item.code));
						if (!selectedCodes.includes(map)) {
							this.$set(this.selectedMaps, this.selectedMaps.length, {
								name: this.curMapName,
								code: map
							});
						}
						// console.log(selectedCodes)
					} else {
						let localtionData = this.data;
						localtionData.district = params.name;
						sessionStorage.setItem("localtionData", JSON.stringify(localtionData));
						// console.log(localtionData);
						this.$router.replace("/MoreData");
					}
				});
			},
			async initMapData(mapJson) {
				let mapData1 = [];
				// console.log(mapJson);
				const {
					data: res
				} = await getChina(this.data);
				let mapNumData = res.data;
				for (let i = 0; i < mapJson.features.length; i++) {
					// console.log(mapJson.features[i].properties.name.substring(0, 2));
					for (let j = 0; j < mapNumData.length; j++) {
						// console.log(mapNumData[j].location);
						if (mapJson.features[i].properties.name.substring(0, 2) == mapNumData[j].location.substring(0, 2)) {
							// console.log(mapNumData[j].location);
							mapData1.push({
								name: mapJson.features[i].properties.name,
								value: [mapJson.features[i].properties.center[0], mapJson.features[i].properties.center[1], mapNumData[j].data]
							});

						}
					}
				}
				// console.log(mapData1);
				return mapData1;

			},
			// 地图标题菜单点击
			chooseMap(item, index) {
				this.selectedMaps.splice(index + 1);
				this.getMapData(item.code, item.name);

			},
			// 浏览器窗口大小改变时，重新加载图表以自适应
			resizeCharts: _debounce(function() {
				this.$echarts.init(document.getElementById("mapChart")).resize();
			}, 500),
			// 获取地图数据
			getMapData(map, mapName) {
				this.$http
					.get(`/static/json/map/${map}.json`)
					.then(res => {
						if (res.status == 200) {
							const mapJSON = res.data;
							if (mapJSON.features[0].properties.level == "province") {
								this.data.province = "";
								this.data.city = "";
							}
							if (mapJSON.features[0].properties.level == "city") {
								this.data.province = mapName;
								this.data.city = "";
							}

							if (mapJSON.features[0].properties.level == "district") {
								this.data.city = mapName;
							}
							this.drawMapChart(this.curMapName, mapJSON);
						}
					})
					.catch(err => {
						this.$message({
							message: err,
							type: "error",
							showClose: true
						});
					});

			},

			// test() {
			// 	let that = this;
			// 	console.log('1');
			// 	let craftChoose = sessionStorage.getItem('craftChoose');
			// 	let categoryChoose = sessionStorage.getItem('categoryChoose');
			// 	if (craftChoose != '' || categoryChoose != '') {
			// 		that.data.craft = sessionStorage.getItem('craftChoose');
			// 		that.data.category = sessionStorage.getItem('categoryChoose');
			// 		that.selectedMaps = [{
			// 			name: "china",
			// 			code: "100000"
			// 		}];
			// 		that.getMapData(that.chinaCode, that.curMapName);
			// 	}
			// },
		},


		watch: {
			data: {
				handler(newData, oldData) {
					// console.log(newData.craft);
					// console.log(this.oldCraft);
					// console.log(newData.category);
					// console.log(this.oldCategory);
					if (this.oldCraft != newData.craft || this.oldCategory != newData.category) {
						console.log("1223")
						this.selectedMaps = [{
							name: "china",
							code: "100000"
						}];
						this.getMapData(this.chinaCode, this.curMapName);
						this.oldCraft = newData.craft;
						this.oldCategory = newData.category;
					}
				},
				deep: true
			},
		},

		mounted() {
			for (let i = 0; i < 7; i++) {
				let a = i + 1;
				this.timeDistribution.push({
					value: "选项" + a,
					label: new Date().getFullYear() - i
				});
			};
			this.getMapData(this.chinaCode, this.curMapName);
			window.addEventListener("resize", this.resizeCharts);

			this.$bus.$on('craftChoose', content => {
				this.oldCraft = this.data.craft;
				this.data.craft = content;
				// console.log(content)
			});
			// this.$bus.$on('categoryChoose', content => {
			// 	console.log(content)
			// });
			// sessionStorage.setItem('craftChoose', this.nullData);
			// sessionStorage.setItem('categoryChoose', this.nullData);
			// window.eventBus.$on('setCraftData', (data) => { // 带参数
			// 	this.data.craft = data;
			// 	// console.log(data);
			// });

			window.eventBus.$on('setCategoryData', (data) => { // 带参数
				this.oldCategory = this.data.category;
				this.data.category = data;
				// console.log(data);
			});

			// 添加对 sessionStorage 的监听
			// window.addEventListener("setItem",() => {
			// 	let that = this;
			// 	console.log('1');
			// 	let craftChoose = sessionStorage.getItem('craftChoose');
			// 	let categoryChoose = sessionStorage.getItem('categoryChoose');
			// 	if (craftChoose != '' || categoryChoose != '') {
			// 		that.data.craft = sessionStorage.getItem('craftChoose');
			// 		that.data.category = sessionStorage.getItem('categoryChoose');
			// 		that.selectedMaps = [{
			// 			name: "china",
			// 			code: "100000"
			// 		}];
			// 		that.getMapData(that.chinaCode, that.curMapName);
			// 	}
			// });

		},

		beforeDestroy() {
			window.addEventListener("resize", this.resizeCharts);
			// 移除对 sessionStorage 的监听
			// window.removeEventListener("setItem", () => {});
			window.eventBus.$off('setCategoryData');
			// window.eventBus.$off('setCraftData');

			this.$bus.$off('craftChoose');

		},

	};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="less" scoped>
	.tabel_Background {
		width: 100%; //3.02rem;
		min-width: 2.96rem;
		height: 69.6%;
		box-sizing: border-box;
	}

	.tabel_Background-wra {
		width: 100%; //3.02rem;
		min-width: 2.96rem;
		height: 100%;
		// border: 1px solid rgb(12, 50, 107);
		background-image: url("../../assets/Panel@2x.png");
		// background-image: url('./../../../assets/mobile/pre-share-page@2x.png');
		background-repeat: no-repeat;
		background-size: 100% 100%; // contain; // cover;
		padding: 2%;
		box-sizing: border-box;
	}

	.chart {
		// background-image: url("../../assets/img/bgImg.png");
		// background-size: 100% 100%;
		width: 100%;
		height: 100%;
		position: relative;

		#mapChart {
			width: 100%;
			height: 100%;
		}

		.mapChoose {
			position: absolute;
			left: 2%; // 20px;
			top: 2%; //25px;
			color: #eee;

			.title {
				padding: 5px;
				border-top: 1px solid rgba(132, 219, 233, 0.8);
				border-bottom: 1px solid rgba(147, 235, 248, 0.8);
				cursor: pointer;
			}


			.icon {
				font-family: "simsun";
				font-size: 6.5px;
				margin: 0 11px;
			}
		}
	}

	.year-cls {
		position: absolute;
		right: 2%;
		top: 2%;
		width: 9%;
		height: 6%;
		border: 1px solid rgb(12, 50, 107);
		background-image: url("../../assets/bg_fxsj@2x.png");
		background-repeat: no-repeat;
		background-size: 100% 100%;
		color: #a9deee;

		.time-cls {
			margin-top: 3%;
			display: inline-block;
		}

		/deep/ .el-select-dropdown__item {
			//单独设置时间分布下拉框字体大小
			font-size: 8px;
			height: 30px;
			line-height: 30px;
		}

		/deep/.el-input__inner {
			font-size: 18px;
			color: #03d5fa;
			padding: 0;
			width: 100%;
			height: 100%;
			background: transparent;
			border: 1px solid #03d5fa;
			text-align: center;
		}

		/deep/.el-select-dropdown__wrap {
			// background-color: bisque !important;
			max-height: 200px !important;
		}

		/deep/ .el-select-dropdown {
			border: 1px solid #03d5fa;
			background-color: #121b33;
			color: #14adff;

			&:hover {
				background-color: #121b33;
			}
		}

		.el-select-dropdown__item {
			color: #03d5fa;
		}

		.el-select-dropdown__item.hover {
			background-color: #0d2a48;
		}

		/deep/.el-input--mini {
			height: 100%;
		}
	}

	.el-input__suffix-inner {
		i {
			display: inline-block;

			&:before {
				display: none;
			}

			background-image: url("../../assets/bg_fxsj@2x.png");
			background-repeat: no-repeat;
			background-size: 100% 100%;
		}
	}

	.icon {
		font-family: "simsun";
		font-size: 6.5px;
		margin: 0 11px;
	}
</style>
